/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.jSkyRoom.generator;

import ru.jSkyRoom.generator.command.ModificationCommand;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import ru.jSkyRoom.support.GrupTypeBuilder;
import ru.jSkyRoom.support.GrupTypeFactory;
import ru.jSkyRoom.interfaces.JSkyMod;
import ru.jSkyRoom.interfaces.major.Major;
import ru.jSkyRoom.interfaces.additional.HasTemplate;
import skyproc.GRUP_TYPE;

/**
 *
 * @author Rakev
 */
public class MajorBuilder<E extends Major> {

    private JSkyMod editingMod;
    private E base;
    private String edid;
    private List<ModificationCommand<E>> commands = new ArrayList<>();

    public MajorBuilder(JSkyMod editingMod, E base) {
        this.editingMod = editingMod;
        this.base = base;
        this.edid = "";
    }

    public MajorBuilder(MajorBuilder<E> otherBuilder) {
        this.editingMod = otherBuilder.editingMod;
        this.base = otherBuilder.base;
        this.edid = otherBuilder.edid;
        commands.addAll(otherBuilder.commands);
    }

    public E getBase() {
        return base;
    }

    public String getEDID() {
        return edid;
    }

    public void setEdid(String edid) {
        this.edid = edid;
    }

    public void addEdidApendix(String edidApendix) {
        this.edid = edid + "_" + edidApendix;
    }

    public MajorBuilder addModification(ModificationCommand<E> command) {
        commands.add(command);
        return this;
    }

    public MajorBuilder addModifications(ModificationCommand<E>... commands) {
        for (ModificationCommand command : commands) {
            addModification(command);
        }
        return this;
    }

    public MajorBuilder addModifications(Iterable<ModificationCommand<E>> commands) {
        for (ModificationCommand command : commands) {
            addModification(command);
        }
        return this;
    }

    public E build() {
        if (edid.isEmpty()) {
            edid = generateRandomEdid();
        }
        E buildingItem = (E) editingMod.makeCopy(base, edid);
        for (ModificationCommand modificationCommand : commands) {
            modificationCommand.apply(buildingItem);
        }
        return buildingItem;
    }

    private String generateRandomEdid() {
        GRUP_TYPE baseGrupType = GrupTypeFactory.create(base);
        String randomEdid = base.getEDID() + getRandomNumber();
        while (editingMod.getMajor(randomEdid, baseGrupType) != null) {
            randomEdid += getRandomNumber();
        }
        return randomEdid;
    }

    private int getRandomNumber() {
        return (int) Math.random() * 10;
    }
}
